<template>
  <div class="role" ref="roleRef">
    <!-- 面包屑导航区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
     <!-- 卡片视图 -->
    <el-card>
      <!-- 添加角色按钮区域 -->
      <el-row>
        <el-col>
          <el-button type="primary" @click="addRole">添加角色</el-button>
        </el-col>
      </el-row>

      <!-- 角色列表区域 -->
      <el-table :data="rolelist" border stripe :height="tHeight">
        <!-- 展开列 -->
        <el-table-column type="expand">
          <template slot-scope="scope">
            <el-row :class="['bdbottom', index === 0 ? 'bdtop' : '', 'vcenter']" v-for="(item,index) in scope.row.children" :key="item.id">
              <!-- 一级权限列表 -->
              <el-col :span="5" :offset="0">
                <el-tag closable @close="removeRightById(scope.row, item.id)">{{item.authName}}</el-tag>
                 <i class="el-icon-caret-right"></i>
              </el-col>
              <!-- 二级，三级权限列表 -->
              <el-col :span="19" :offset="0">
                 <!-- 二级 -->
                   <el-row :class="[index2 === 0 ? '' : 'bdtop', 'vcenter']" v-for="(item2,index2) in item.children" :key="item2.id">
                     <el-col :span="6">
                        <el-tag type="success" closable @close="removeRightById(scope.row, item2.id)">{{item2.authName}}</el-tag>
                        <i class="el-icon-caret-right"></i>
                     </el-col>
                     <!-- 三级 -->
                     <el-col :span="18">
                        <el-tag type="warning" v-for="item3 in item2.children" :key="item3.id" closable @close="removeRightById(scope.row, item3.id)">{{item3.authName}}</el-tag>
                     </el-col>
                   </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <!-- 索引列 -->
        <el-table-column type="index"></el-table-column>
        <el-table-column label="角色名称" prop="roleName"></el-table-column>
        <el-table-column label="角色描述" prop="roleDesc"></el-table-column>
        <el-table-column label="操作" width="300px">
          <template slot-scope="scope">
            <el-button @click="edit(scope.row.id)" size="mini" type="primary" icon="el-icon-edit">编辑</el-button>
            <el-button @click="deleteRole(scope.row.id)" size="mini" type="danger" icon="el-icon-delete">删除</el-button>
            <el-button size="mini" type="warning" icon="el-icon-setting" @click="showSetRightDialog(scope.row)">分配权限</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
     <!-- 分配权限的对话框 -->
    <el-dialog title="分配权限" :visible.sync="setRightDialogVisible" width="50%" @close="setRightDialogClosed">
      <!-- 树形控件 -->
      <el-tree class="tree" :data="rightslist" :props="treeProps" show-checkbox node-key="id" default-expand-all :default-checked-keys="defKeys" ref="treeRef"></el-tree>
      <span slot="footer" class="dialog-footer">
        <el-button @click="setRightDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="updateRights">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 添加角色的对话框 -->
    <el-dialog title="添加角色" :visible.sync="addDialogVisible" width="50%" @close="addDialogClosed">
      <!-- 内容主体区域 -->
      <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="90px">
        <el-form-item label="角色名" prop="roleName">
          <el-input v-model="addForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="addForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <!-- 底部区域 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="roleComit">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 修改角色dialog -->
     <el-dialog title="修改角色" :visible.sync="editDialogVisible" width="50%" @close="editDialogClosed">
      <!-- 内容主体区域 -->
      <el-form :model="editForm" :rules="addFormRules" ref="editFormRef" label-width="90px">
        <el-form-item label="角色名" prop="roleName">
          <el-input v-model="editForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="editForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <!-- 底部区域 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editRole">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script scoped>
import { getRoles, deleteRight, getRightsTree, upadteRight, addRole, getRoleById, editRoleInfo, deleteR } from 'network/api/power.js'
export default {
  name: 'Role',
  data () {
    return {
      // 表格的高度
      tHeight: undefined,
      // 所有角色列表数据
      rolelist: [],
      // 控制分配权限对话框的显示与隐藏
      setRightDialogVisible: false,
      // 所有权限的数据
      rightslist: [],
      // 树形控件的属性绑定对象
      treeProps: {
        label: 'authName',
        children: 'children'
      },
      // 默认选中的节点Id值数组
      defKeys: [],
      // 当前即将分配权限的角色id
      roleId: '',
      addDialogVisible: false,
      addForm: {
        roleName: '',
        roleDesc: ''
      },
      addFormRules: {
        roleName: [
          { required: true, message: '请输入角色名', trigger: 'blur' }
        ],
        roleDesc: [
          { required: true, message: '请输入角色的详细描述', trigger: 'blur' }
        ]
      },
      editDialogVisible: false,
      editForm: {}

    }
  },
  created () {
    this._getRoleList()
  },
  mounted () {
    this.tHeight = this.$refs.roleRef.offsetHeight - 125
  },
  methods: {
    async _getRoleList () {
      const res = await getRoles()
      if (res.meta.status !== 200) {
        return this.$message.error('获取角色列表失败！')
      }
      this.rolelist = res.data
      console.log(this.rolelist)
    },
    // 删除权限
    async removeRightById (role, id) {
      // 弹窗提示用户是否要删除
      const confirmResult = await this.$confirm(
        '此操作将永久删除该文件, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).catch(err => err)
      if (confirmResult !== 'confirm') {
        return this.$message.info('取消了删除!')
      }
      // 删除角色对用的权限数据
      const res = await deleteRight(role.id, id)
      if (res.meta.status !== 200) {
        return this.$message.error('删除权限失败!')
      }
      // 更新角色列表
      // this._getRoleList() // 会关闭role table列表
      role.children = res.data
    },
    async showSetRightDialog (role) {
      this.roleId = role.id
      const res = await getRightsTree()
      if (res.meta.status !== 200) {
        return this.$message.error('获取权限数据失败！')
      }
      // 把获取到的权限数据保存到 data 中
      this.rightslist = res.data
      console.log(this.rightslist)
      // 递归获取三级节点的Id
      this.getLeafKeys(role, this.defKeys)
      // 打开分配权限对话框
      this.setRightDialogVisible = true
    },
    // 监听分配权限对话框的关闭事件 （清空）
    setRightDialogClosed () {
      this.defKeys = []
    },
    // 点击保存分配权限
    async updateRights () {
      const keys = [
        ...this.$refs.treeRef.getCheckedKeys(),
        ...this.$refs.treeRef.getHalfCheckedKeys()
      ]
      const ids = keys.join(',')
      const res = await upadteRight(this.roleId, ids)
      if (res.meta.status !== 200) {
        return this.$message.error('分配权限失败！')
      }
      this.$message.success('分配权限成功！')
      this._getRoleList()
      this.setRightDialogVisible = false
    },
    getLeafKeys (node, arr) {
      // 如果当前 node 节点不包含 children 属性，则是三级节点
      if (!node.children) {
        return arr.push(node.id)
      }

      node.children.forEach(item => this.getLeafKeys(item, arr))
    },
    addRole () {
      this.addDialogVisible = true
    },
    // 添加新角色
    roleComit () {
      this.$refs.addFormRef.validate(async valid => {
        if (!valid) return '' // 验证不通过
        // 向后端添加角色
        const res = await addRole(this.addForm)
        if (res.meta.status !== 201) {
          this.$message.error('添加角色失败')
        }
        this.$message.success('添加角色成功')
        // 隐藏对话框
        this.addDialogVisible = false
        // 重新获取角色列表数据
        this._getRoleList()
      })
    },
    // 关闭add对话框，清空数据
    addDialogClosed () {
      this.$refs.addFormRef.resetFields()
    },
    // 点击编辑按钮
    async edit (id) {
      const res = await getRoleById(id)
      if (res.meta.status !== 200) return this.$message.error('获取角色失败!')
      this.editForm = res.data
      this.editDialogVisible = true
    },
    editDialogClosed () {
      this.$refs.editFormRef.resetFields()
    },
    editRole () {
      this.$refs.editFormRef.validate(async valid => {
        if (!valid) return ''
        // 将修改角色信息保存至后端
        const res = await editRoleInfo(this.editForm.roleId, {
          roleName: this.editForm.roleName,
          roleDesc: this.editForm.roleDesc
        })
        if (res.meta.status !== 200) {
          return this.$message.error('更改角色信息失败!')
        }
        // 关闭对话框
        this.editDialogVisible = false
        // 刷新用户列表
        this._getRoleList()
        // 提示修改成功
        this.$message.success('更新角色信息成功!')
      })
    },
    // 删除角色
    async deleteRole (id) {
      const confirmRes = await this.$confirm(
        '此操作将永久删除该角色, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).catch(err => err)
      if (confirmRes !== 'confirm') {
        return this.$message.info('已取消删除')
      }
      const res = await deleteR(id)
      if (res.meta.status !== 200) return this.$message.error('删除角色失败!')
      this._getRoleList()
    }

  }
}
</script>

<style lang='less' scoped>
  .role{
    height: 100%;
    /deep/ .el-tag {
      margin: 7px;
    }

    .bdtop {
      border-top: 1px solid #eee;
    }

    .bdbottom {
      border-bottom: 1px solid #eee;
    }

    .vcenter {
      display: flex;
      align-items: center;
    }
    .tree {
      height:290px;
      overflow-y: scroll;
    }
  }
</style>
